package com.juhe.transmission.servlet.view;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.juhe.transmission.FileUtils;

public class FileServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		super.doGet(request, response);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String sourceFileName = request.getParameter("file");

		if(sourceFileName != null && !sourceFileName.trim().equals("")){
			File sourceFile = new File(sourceFileName);
			this.file(sourceFile, request);
		}else{
			File[] roots = File.listRoots();
			request.setAttribute("roots" , roots);
			for(int i = 0; i < roots.length; i ++){
				File root = roots[i];
				this.file(root, request);
			}
		}

		request.getRequestDispatcher("readFile.jsp").forward(request, response);

	}
	
	public void file(File sourceFile, HttpServletRequest request){

		List<String> allFileList = new ArrayList<String>();
		List<String> allDirList = new ArrayList<String>();
		
		new FileUtils().listAllFile(sourceFile, allFileList, allDirList);
		
		request.setAttribute("root", sourceFile);
		request.setAttribute("allFileList" + sourceFile.getPath(), allFileList);
		request.setAttribute("allDirList" + sourceFile.getPath(), allDirList);
	}
	
}


